import React, { useState } from 'react'

import axios from 'axios'

import PubSub from 'pubsub-js'

export default function Header() {
  //在state定义一个初始值为空
  const [value, setValue] = useState('')

  //获取表单自身的值 e.target.value
  const formData = (e) => {
    //console.log(e.target.value);
    //设置到state中
    setValue(e.target.value)
  }

  //点击搜索的时候获取到表格中的值然后发送axios请求
  const sendRequest = async () => {
    PubSub.publish('github',{isInit: false, isSearch: true, data: []})

    // 拿到state中的值 进行axios请求
    //这里的axios请求是异步的 所有需要等待 等待axios请求返回的值
    const axiosValue = await axios.get('https://api.github.com/search/users?q=' + value)
    //发布
    PubSub.publish('github',{isInit: false, isSearch: false, data: axiosValue.data.items})
  }

  return (
    <section className="jumbotron">
      <h3 className="jumbotron-heading">Search Github Users</h3>
      <div>
        <input type="text" onChange={formData} placeholder="enter the name you search" />&nbsp;
        <button onClick={sendRequest}>Search</button>
      </div>
    </section>
  )
}
